package cn.edu.seu.ssny.socket;

import cn.edu.seu.ssny.entity.*;
import cn.edu.seu.ssny.service.*;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;

import static cn.edu.seu.ssny.common.utils.DateUtils.stampToDate;


@Component
public class XMLHandler {
    private static final Logger logger = Logger.getLogger(MyServerHandler.class.getName());

    @Autowired
    private IDeviceService deviceService;
    @Autowired
    private IDeviceDataService deviceDataService;
    @Autowired
    private IDeviceDataStdService deviceDataStdService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IGatewayService gatewayService;
    @Autowired
    private IAlarmService alarmService;

    private static XMLHandler xmlHandler;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        xmlHandler = this;
        xmlHandler.deviceService = this.deviceService;
        xmlHandler.deviceDataService = this.deviceDataService;
        xmlHandler.projectService = this.projectService;
        xmlHandler.gatewayService = this.gatewayService;
        xmlHandler.alarmService = this.alarmService;
    }

    public static void handler(String body) throws DocumentException {
        logger.info("==============================================================");
        logger.info(body);
        Document document = null;
        try {
            document = DocumentHelper.parseText(body);
            logger.info("==============================================");
            logger.info(document.toString());
        } catch (DocumentException e) {
            e.printStackTrace();
        }

        try {
            String buildingId = document.selectSingleNode("//root/common/building_id").getStringValue();
            String gatewayId = document.selectSingleNode("//common/gateway_id").getStringValue();
            Node stamptime = document.selectSingleNode("//data/time");
            Date datetime = stampToDate(stamptime.getStringValue());
            List<Node> data = document.selectNodes("//data/meter");


            Project project = xmlHandler.projectService.findByIdentification(buildingId);
            Gateway gateway = xmlHandler.gatewayService.findByIdentification(gatewayId);
            logger.log(Level.WARNING, "传入报文：" + body);
            for (Node meter : data) {
//                logger.log(Level.WARNING,"传入数据："+meter.valueOf("@id") + ": "+ meter.getStringValue());
                try {
                    double meterData = Double.parseDouble(meter.getStringValue().trim());
                    Device device = xmlHandler.deviceService.findByProjectAndGatewayAndTag(project, gateway, meter.valueOf("@id"));
                    xmlHandler.deviceDataService.newDataProcess(device, datetime, meterData);
                    System.out.println(device.getId() + device.getTemplate().getName());
                    if (device.getTemplate().getName().equals("报警")) { //处理报警信号
                        Integer dataInt = (int) (meterData);
                        if (dataInt == 1) {
                            Optional<Alarm> alarmOptional = xmlHandler.alarmService.findFirstByDeviceOrderByCreateTimeDesc(device);
                            if (alarmOptional.isPresent() && !alarmOptional.get().getStatus()) {
                                System.out.println(alarmOptional.get().getStatus());
                                Alarm alarm = alarmOptional.get();
                                alarm.setCreateTime(datetime);
                                xmlHandler.alarmService.updateCreateTime(alarm);
                            } else {
                                Alarm alarm = new Alarm();
                                alarm.setCreateTime(datetime);
                                alarm.setDevice(device);
                                alarm.setName(device.getName());
                                alarm.setEnterprise(project.getEnterprise());
                                alarm.setProject(project);
                                xmlHandler.alarmService.create(alarm);
                            }
                        }
                    }

                } catch (Exception e) {
                    logger.info("=============================================");
                    e.printStackTrace();
                }
            }
        } catch (NullPointerException e) {
            logger.info("===========================================================");
            logger.log(Level.WARNING, "空指针错误\r\n" + body);
            logger.log(Level.WARNING, "解析\r\n" + DocumentHelper.parseText(body));
            logger.log(Level.WARNING, "调用栈：", e);
        }
    }


}
